﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using Cms.Web.Framework.DashboardGadgets;
using Cms.Web.Framework.Infrastructure;

namespace Cms.Web.UI.Admin
{
    public partial class Dashboard : AdminPage, IDashboardView
    {
        private DashboardPresenter _presenter;

        #region IDashboardView Members

        public void SetGadgets(IList<DashboardGadget> gadgets)
        {
            rpGadgets.DataSource = gadgets;
            rpGadgets.DataBind();
        }


        public string ContextTranslationFile
        {
            get { return "Admin/Translations/Dashboard.xml"; }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _presenter = new DashboardPresenter(this);
            _presenter.Initialize();
            HeadingIcon = litIcon.Text;
            HeadingText = GetText(this, "Heading");
        }


        protected void rpGadgets_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var gadget = (DashboardGadget)e.Item.DataItem;
            var pnlGadgetContainer = (Panel)e.Item.FindControl("pnlGadgetContainer");
            try
            {
                var baseGadget = (BaseGadget)Page.LoadControl("~/Admin/DashboardGadgets/" + gadget.Filename);
                baseGadget.Gadget = gadget; // Inject the underlying domain object
                baseGadget.Administrator = _presenter.Administrator;
                baseGadget.RepositoryFactory = new RepositoryFactory();
                pnlGadgetContainer.Controls.Add(baseGadget);
            }
            catch (Exception ex)
            {
                pnlGadgetContainer.Controls.Add(new LiteralControl("Failed to load " + gadget.GetFilenameWithoutExtension()));
            }
        }
    }
}